package com.meihua.workflow.controller;

import cn.hutool.core.util.StrUtil;

import com.meihua.workflow.constants.R;
import com.meihua.workflow.model.TaskTemplate;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/task")
public class TaskController {
    @Resource
    private TaskService taskService;
    @Resource
    private RuntimeService runtimeService;
    //通过审批，进入下一节点
    @GetMapping("/{assignee}/{taskId}/{flag}")
    public R passPersonalTask(@PathVariable("assignee") String assignee, @PathVariable("taskId") String taskId, @PathVariable(value = "flag",required = false ) String flag) {
        if (assignee == null || taskId == null) {
            return R.error("请求参数错误");
        }
        System.out.println("完成审批任务==========");
        System.out.println("任务id：" + taskId);
        System.out.println("审批人：" + assignee);
        Task task = this.taskService.createTaskQuery().taskId(taskId).taskAssignee(assignee).singleResult();
//        if(Objects.equals(task.getName(), "教师审批节点")){
//            this.taskService.setVariable(taskId,"isPassed",flag);
//        }
        this.taskService.addComment(taskId, task.getProcessInstanceId(), "审批通过");
        this.taskService.complete(task.getId());
        System.out.println("完成审批任务==========");
        System.out.println("任务id：" + task.getId());
        System.out.println("任务名称：" + task.getName());
        System.out.println("该任务的负责人：" + task.getAssignee());
        System.out.println("该任务所属的流程实例id：" + task.getProcessInstanceId());
        System.out.println("该任务定义的key：" + task.getTaskDefinitionKey());
        TaskTemplate taskTemplate = new TaskTemplate();
        taskTemplate.setTaskId(task.getId());
        taskTemplate.setTaskAssignee(assignee);
        taskTemplate.setTaskName(task.getName());
        taskTemplate.setTaskProcessInstanceId(task.getProcessInstanceId());
        taskTemplate.setTaskParentTaskId(task.getParentTaskId());
//        String processInstanceName = this.runtimeService.startProcessInstanceById(task.getProcessInstanceId()).getProcessDefinitionKey();
//        taskTemplate.setTaskProcessInstanceName(processInstanceName);
        return R.success(taskTemplate);
    }
    @GetMapping("/{assignee}")
    public R selectOnesTasks(@PathVariable("assignee") String assignee) {
        if (StrUtil.isEmpty(assignee)) {
            return R.error("参数错误:请确定具体的审批人");
        }
        // 1. 创建ProcessEngine
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        // 2. 获取RuntimeServic
        TaskService taskService = processEngine.getTaskService();
        List<Task> tasksList = taskService.createTaskQuery().taskAssignee(assignee).list();
        RuntimeService runtimeService = processEngine.getRuntimeService();
        TaskTemplate taskTemplate = new TaskTemplate();
        List<TaskTemplate> taskTemplates = new ArrayList<>();
        for (Task task : tasksList) {
            String parentTaskName = null;
            System.out.println("==========================");
            System.out.println("-----任务id：---" + task.getId());
            System.out.println("-----当前任务名称：---" + task.getName());
            System.out.println("-----任务审批人：---" + task.getAssignee());
            System.out.println("-----任务所属流程id：---" + task.getProcessInstanceId());
            String processInstanceName = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult().getName();
            System.out.println("-----任务所属流程Name：---" + processInstanceName);
            System.out.println("-----上级任务id：---" + task.getParentTaskId());
            if (task.getParentTaskId() != null) {
                parentTaskName = taskService.createTaskQuery().taskId(task.getParentTaskId()).singleResult().getName();
                System.out.println("-----上级任务Name：---" + parentTaskName);
            }
            taskTemplate.setTaskId(task.getId());
            taskTemplate.setTaskAssignee(assignee);
            taskTemplate.setTaskName(task.getName());
            taskTemplate.setTaskProcessInstanceId(task.getProcessInstanceId());
            taskTemplate.setTaskParentTaskId(task.getParentTaskId());
            taskTemplate.setTaskParentTaskName(parentTaskName);
            taskTemplate.setTaskProcessInstanceName(processInstanceName);
            taskTemplates.add(taskTemplate);
        }
        return R.success(taskTemplates);
    }

    //放弃申领到的任务
    @GetMapping("/c/{assignee}/{taskId}")
    public R cancelTask(@PathVariable("assignee") String assignee, @PathVariable("taskId") String taskId){
        // 获取当前用户
        Task task = taskService.createTaskQuery()
                .taskAssignee(assignee)
                .taskId(taskId)
//                .processInstanceBusinessKey(businessKey)
                .singleResult();
        if (task != null) {
            taskService.setAssignee(task.getId(), null);
            System.out.println(assignee + "放弃了任务！");
        }
    return  R.success();
    }
    //申领或转移任务
    @GetMapping("/g/{assignee}/{taskId}")
    public R getTask(@PathVariable("assignee") String toAssignee, @PathVariable("taskId") String taskId){
            Task task =null;
            if (StrUtil.isEmpty(toAssignee)){
                task = this.taskService.createTaskQuery().taskId(taskId).singleResult();
            }else {
                task = this.taskService.createTaskQuery().taskAssignee(toAssignee).taskId(taskId).singleResult();
            }
        if (task == null) {
           return R.error("任务不存在！");
        }
        taskService.claim(taskId, toAssignee);
        System.out.println(toAssignee + "申领到了任务！");
    return R.success(toAssignee + "申领到了任务！");
    }
}
